import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layout/index.vue'

const constantRoutes = [
  {
    path: '/redirect',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '/redirect/:path(.*)',
        component: () => import('@/views/redirect/redirect.vue'),
      },
    ],
  },
  {
    path: '/login',
    name: 'Login',
    hidden: true,
    component: () => import('@/views/login/login.vue'),
    meta: {
      title: '登录',
      icon: 'el-icon-s-home',
      noCache: true, // 没有缓存
    },
  },
  {
    path: '/404',
    component: () => import('@/views/error-page/404.vue'),
    hidden: true,
  },
  {
    path: '/401',
    component: () => import('@/views/error-page/401.vue'),
    hidden: true,
  },
]

const asyncRoutes = [
  {
    path: '/',
    name: '主页',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('@/views/home/home.vue'),
        meta: {
          title: '主页',
          noCache: true,
        },
      },
    ],
  },
  { path: '/:pathMatch(.*)', redirect: '/404', hidden: true },
]

const createRouters = createRouter({
  history: createWebHistory(),
  routes: constantRoutes.concat(asyncRoutes),
  scrollBehavior: () => ({ left: 0, top: 0 }), //  return 期望滚动到哪个的位置
})

const router = createRouters

export function resetRouter() {
  const WHITE_NAME_LIST = ['Login']
  router.getRoutes().forEach(route => {
    const { name } = route
    if (name && !WHITE_NAME_LIST.includes(name)) {
      router.hasRoute(name) && router.removeRoute(name)
    }
  })
}

export default router
